package com.cf.r1031_d;

import java.io.*;

public class d {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer in = new StreamTokenizer(br);
        PrintWriter out = new PrintWriter(System.out);
        in.nextToken();
        int t = (int) in.nval;
        while (t-- > 0) {
            in.nextToken(); n = (int) in.nval;
            arrplayer = new int[n + 1];
            arrester = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                in.nextToken();
                arrplayer[i] = (int) in.nval;
            }
            for (int i = 1; i <= n; i++) {
                in.nextToken();
                arrester[i] = (int) in.nval;
            }
            int l = 0, r = n;
            while (l < r) {
                int m = l + ((r - l + 1) >> 1);
                if (check(m)) {
                    l = m;
                } else {
                    r = m - 1;
                }
            }
            out.println(l);
        }
        out.flush();
        out.close();
        br.close();
    }

    public  static int[] arrplayer;
    public static int[] arrester;
    public  static int n;

    public static boolean check(int m) {
        // mn，玩家数组前m个元素的最小值
        // mn2，玩家数组前m个元素的次小值
        // mx，玩家数组后n-m个元素的最大值
        int mn = Integer.MAX_VALUE, mn2 = Integer.MAX_VALUE, mx = 0;
        for (int i = 1; i <= m; i++) {
            if (arrplayer[i] < mn) {
                mn2 = mn;
                mn = arrplayer[i];
            } else if (arrplayer[i] < mn2) {
                mn2 = arrplayer[i];
            }
        }
        for (int i = m + 1; i <= n; i++) {
            mx = Math.max(mx, arrplayer[i]);
        }
        // target，庄家数组前n-m+1个元素的最小值
        int target = Integer.MAX_VALUE;
        for (int i = 1; i <= n - m + 1; i++) {
            target = Math.min(target, arrester[i]);
        }
        // mn 和 mx 交换
        // 如果mx > mn2，说明mn成功被交换
        if (mx > mn2) {
            // 此时如果mn2 > target，说明可以得到m分
            // 否则，说明无法得到m分
            return mn2 > target;
        } else {
            // mx 没有 mn2大，甚至没有mn大
            // 此时如果mn或mx > target，说明可以得到m分
            return Math.max(mn, mx) > target;
        }
    }

}
